package net.zrnecko.km.client;

import java.util.ArrayList;
import java.util.List;

import net.zrnecko.km.dto.PlayerDTO;
import net.zrnecko.km.dto.TournamentDTO;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelReader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class KalicMasters implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	// private LoginInfo loginInfo = null;
	private VerticalPanel loginPanel = new VerticalPanel();
	private Label loginLabel = new Label(
			"Please sign in to your Google Account to access the StockWatcher application.");
	private Label loggedIn = new Label("I'm logged in");
	private Anchor signInLink = new Anchor("Sign In");
	private Anchor signOutLink = new Anchor("Sign Out");
	private LoginInfo loginInfo = null;
	
	private	VerticalPanel vP5 = new VerticalPanel();
	private final TabItem adminTab = new TabItem("Admin");

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	private final PersistenceServiceAsync persistenceService = GWT
			.create(PersistenceService.class);

	private void loadLogin() {
		signInLink.setHref(loginInfo.getLoginUrl());
		loginPanel.add(loginLabel);
		loginPanel.add(signInLink);
		
//		RootPanel.get("stockList").add(loginPanel);

		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
	}

	private void loadAdminUi() {
		loginPanel.add(loggedIn);
		
		final Label testLabel = new Label();
		testLabel.setText("Admin page");
		RootPanel.get().add(testLabel);

		final Label debugLabel = new Label();
		debugLabel.setText("Submitting file...");
		debugLabel.setVisible(false);

		// Enclosing form
		final FormPanel form = new FormPanel();
		form.setEncoding(FormPanel.ENCODING_MULTIPART);
		form.setMethod(FormPanel.METHOD_POST);
		form.setAction("/kalicmasters/upload");

		// Add an event handler to the form.
		form.addSubmitHandler(new SubmitHandler() {

			public void onSubmit(SubmitEvent event) {
				// TODO Auto-generated method stub
				debugLabel.setVisible(true);
			}

		});

		// File upload element
		final FileUpload fileUpload = new FileUpload();
		fileUpload.setName("fileUpload");
		// fileUpload.ensureDebugId("cwFileUpload");

		// List box determining uploaded file type
		final ListBox fileTypeDropDown = new ListBox(false);
		fileTypeDropDown.setName("fileTypeDropDown");
		String[] fileTypes = { "Tournaments", "Results", "Players" };
		for (int i = 0; i < fileTypes.length; i++) {
			fileTypeDropDown.addItem(fileTypes[i]);
		}

		//
		final Label infoMessage = new Label("Submitting...");
		infoMessage.setVisible(false);

		// Submit button
		final Button submitButton = new Button("Submit", new ClickHandler() {
			public void onClick(ClickEvent event) {
				form.submit();
				infoMessage.setVisible(true);
			}
		});

		final VerticalPanel panel = new VerticalPanel();
		
		
		

		// Composing form
		form.setWidget(panel);
		
		
		
		panel.add(fileUpload);
		panel.add(fileTypeDropDown);
		panel.add(submitButton);
		panel.add(infoMessage);
		panel.add(debugLabel);
		
	    final PersistenceServiceAsync ps = GWT
			.create(PersistenceService.class);
		final VerticalPanel panel2 = new VerticalPanel();
		final TextBox playerName = new TextBox();
		final Label status = new Label();
		panel2.add(playerName);
		
		final Button addPlayerButton = new Button("Add player", new ClickHandler() {
			public void onClick(ClickEvent event) {
				final String name = playerName.getText();
				// TODO name validation - not empty?
				PlayerDTO p = new PlayerDTO();
				p.setName(name);
				ps.persistPlayer(p, new AsyncCallback<Void>() {
					
					public void onSuccess(Void result) {
						status.setText("Player saved");
						
					}
					
					public void onFailure(Throwable caught) {
						status.setText("Saving player failed");
						
					}
				});
				
				
				
				
				
				
			}
		});
		panel2.add(addPlayerButton);
		panel2.add(status);
		loginPanel.add(panel);
		loginPanel.add(panel2);

	}

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		final Button sendButton = new Button("Send");
		final TextBox nameField = new TextBox();
		nameField.setText("GWT User");

		// final DecoratedTabPanel tabPanel = new DecoratedTabPanel();
		// tabPanel.setAnimationEnabled(false);
		// tabPanel.setSize("1024px", "450px");

		TabPanel tabPanel = new TabPanel();
		tabPanel.setPlain(true);

		ContentPanel cp = new ContentPanel();
		cp.setBodyBorder(false);
		// cp.setIcon(Examples.ICONS.table());
		cp.setHeading("Basic Grid");
		cp.setButtonAlign(HorizontalAlignment.CENTER);
		cp.setLayout(new FitLayout());
		cp.setSize(600, 300);

		VerticalPanel vP1 = new VerticalPanel();
		vP1.setHeight("400px");
		// tabPanel.add(vP1, "Přehled");
		TabItem overviewTab = new TabItem("Přehled");
		overviewTab.add(vP1);
		tabPanel.add(overviewTab);

		Grid grid = new Grid(2, 2);
		grid.setCellSpacing(15);

		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

		ColumnConfig column = new ColumnConfig();
		column.setId("");
		column.setHeader("Pořadí");
		column.setWidth(50);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("symbol");
		column.setHeader("Symbol");
		column.setWidth(100);
		configs.add(column);

		column = new ColumnConfig();
		column.setId("last");
		column.setHeader("Last");
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setWidth(75);
		// column.setRenderer(gridNumber);
		configs.add(column);

		column = new ColumnConfig("change", "Change", 100);
		column.setAlignment(HorizontalAlignment.RIGHT);
		// column.setRenderer(change);
		configs.add(column);

		column = new ColumnConfig("date", "Last Updated", 100);
		column.setAlignment(HorizontalAlignment.RIGHT);
		column.setDateTimeFormat(DateTimeFormat.getShortDateFormat());
		configs.add(column);

		/*
		 * TournamentResult tr1 = new TournamentResult(); List<Result>
		 * tr1Results = new ArrayList<Result>(); Result r1 = new Result();
		 * r1.setResult(190); tr1Results.add(r1); Result r2 = new Result();
		 * r2.setResult(190); tr1Results.add(r2); Result r3 = new Result();
		 * r3.setResult(190); tr1Results.add(r3);
		 */

		// ListStore<> store = new ListStore<Stock>();
		// store.add(TestData.getStocks());

		ColumnModel cm = new ColumnModel(configs);

		// com.extjs.gxt.ui.client.widget.grid.Grid resultGrid = new Grid(store,
		// cm);

		ContentPanel lastTourContentPanel = new ContentPanel();
		lastTourContentPanel.setHeading("Poslední turnaj");
		lastTourContentPanel.setSize("300px", "600px");
		grid.setWidget(0, 0, lastTourContentPanel);

		ContentPanel pointRankingContentPanel = new ContentPanel();
		pointRankingContentPanel.setHeading("Bodovací žebříček");
		pointRankingContentPanel.setSize("300px", "600px");
		grid.setWidget(0, 1, pointRankingContentPanel);

		ContentPanel avgRankingContentPanel = new ContentPanel();
		avgRankingContentPanel.setHeading("Průměrový žebříček");
		avgRankingContentPanel.setSize("300px", "600px");
		grid.setWidget(1, 0, avgRankingContentPanel);

		final ContentPanel bestResultsContentPanel = new ContentPanel();

		bestResultsContentPanel.setHeading("Nejlepší výkony");
		bestResultsContentPanel.setSize("300px", "600px");

		final Label warning = new Label("Saving tournament failed");
		warning.setVisible(false);

		/*
		 * GWT.log("Before saving tour", null); TournamentDTO tdto = new
		 * TournamentDTO(); tdto.setTournamentId(2); tdto.setDate(new Date());
		 * persistenceService.persistTournament(tdto, new AsyncCallback<Void>()
		 * {
		 * 
		 * public void onFailure(Throwable caught) { warning.setVisible(true);
		 * // TODO Auto-generated method stub
		 * 
		 * }
		 * 
		 * public void onSuccess(Void result) { // TODO Auto-generated method
		 * stub
		 * 
		 * } }); GWT.log("After saving tour", null);
		 */

		RpcProxy<List<TournamentDTO>> proxy = new RpcProxy<List<TournamentDTO>>() {
			@Override
			public void load(Object loadConfig,
					AsyncCallback<List<TournamentDTO>> callback) {
				persistenceService.listTournaments(callback);
			}
		};
		BeanModelReader reader = new BeanModelReader();

		// CopyOfTournament cot = new CopyOfTournament(7, new Date());
		// CopyOfTournament cot2 = new CopyOfTournament(23, new Date());
		// List l = new ArrayList();
		// l.add(cot);
		// l.add(cot2);

		// loader and store
		ListLoader<ListLoadResult<ModelData>> loader = new BaseListLoader<ListLoadResult<ModelData>>(
				proxy, reader);
		ListStore<BeanModel> store = new ListStore<BeanModel>(loader);
		loader.load();

		// List<BeanModel> model = factory.createModel(result);
		// ListStore<BeanModel> store = new ListStore<BeanModel>();
		// store.add(model);
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		ColumnConfig tourDateColumn = new ColumnConfig("date", "Datum", 100);
		tourDateColumn
				.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(new ColumnConfig("tournamentId", "#", 200));
		columns.add(tourDateColumn);
		ColumnModel cm1 = new ColumnModel(columns);
		com.extjs.gxt.ui.client.widget.grid.Grid<BeanModel> uiGrid = new com.extjs.gxt.ui.client.widget.grid.Grid<BeanModel>(
				store, cm1);
		uiGrid.setAutoExpandColumn("date");
		uiGrid.setAutoHeight(true);
		bestResultsContentPanel.add(uiGrid);
		// column model
		// final com.extjs.gxt.ui.client.widget.grid.Grid<BeanModel> uiGrid =
		// new com.extjs.gxt.ui.client.widget.grid.Grid();

		grid.setWidget(1, 1, bestResultsContentPanel);

		vP1.add(grid);

		VerticalPanel vP2 = new VerticalPanel();
		vP2.add(nameField);
		vP2.add(sendButton);
		// tabPanel.add(vP2, "Turnaje");
		TabItem tournamentsTab = new TabItem("Turnaje");
		tournamentsTab.add(vP2);
		tabPanel.add(tournamentsTab);

		// button.draw();

		// or
		// RootPanel.get().add(button);

		VerticalPanel vP3 = new VerticalPanel();
		// tabPanel.add(vP3, "Hráči");
		TabItem playersTab = new TabItem("Hráči");
		playersTab.add(vP3);
		tabPanel.add(playersTab);

		VerticalPanel vP4 = new VerticalPanel();
		vP4.add(cp);
		// tabPanel.add(vP4, "Pravidla");
		TabItem rulesTab = new TabItem("Pravidla");
		rulesTab.add(vP4);
		tabPanel.add(rulesTab);

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		VerticalPanel vP5 = new VerticalPanel();
		//TabItem adminTab = new TabItem("Admin");
//		adminTab.add(loginPanel);
		tabPanel.add(adminTab);

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		// RootPanel.get("nameFieldContainer").add(nameField);
		// RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get().add(tabPanel);
		RootPanel.get().add(warning);

		LoginServiceAsync loginService = GWT.create(LoginService.class);
		loginService.login(GWT.getHostPageBaseURL(),
				new AsyncCallback<LoginInfo>() {
					public void onFailure(Throwable error) {
					}

					public void onSuccess(LoginInfo result) {
						loginInfo = result;
						adminTab.add(loginPanel);
						if (loginInfo.isLoggedIn()) {
							loadAdminUi();
						} else {
							loadLogin();
						}
					}

				});

		HTML appEngineBadge = new HTML(
				"<img src=\"http://code.google.com/appengine/images/appengine-silver-120x30.gif\" alt=\"Powered by Google App Engine\" />");
		RootPanel.get().add(appEngineBadge);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);

		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void sendNameToServer() {
				sendButton.setEnabled(false);
				String textToServer = nameField.getText();
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								closeButton.setFocus(true);
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		nameField.addKeyUpHandler(handler);
		/*
		 * persistenceService .listTournaments(new
		 * AsyncCallback<List<TournamentDTO>>() {
		 * 
		 * public void onFailure(Throwable caught) { // TODO Auto-generated
		 * method stub
		 * 
		 * }
		 * 
		 * public void onSuccess(List<TournamentDTO> result) { // TODO
		 * Auto-generated method stub BeanModelFactory factory =
		 * BeanModelLookup.get() .getFactory(TournamentDTO.class);
		 * 
		 * List<BeanModel> model = factory.createModel(result);
		 * ListStore<BeanModel> store = new ListStore<BeanModel>();
		 * store.add(model); List<ColumnConfig> columns = new
		 * ArrayList<ColumnConfig>(); columns.add(new
		 * ColumnConfig("tournamentId", "#", 200)); columns.add(new
		 * ColumnConfig("date", "Datum", 100)); ColumnModel cm1 = new
		 * ColumnModel(columns);
		 * com.extjs.gxt.ui.client.widget.grid.Grid<BeanModel> uiGrid = new
		 * com.extjs.gxt.ui.client.widget.grid.Grid<BeanModel>( store, cm1);
		 * uiGrid.setAutoExpandColumn("date");
		 * bestResultsContentPanel.add(uiGrid); } });
		 */
	}
}
